package com.etao.tools.api;

import com.etao.tools.Iservice.ITurnOverService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

/**
 * Created by lyp on 2016/8/11.
 */
public class TurnOverApi implements ServletContextListener {
    private static Logger logger = LoggerFactory.getLogger("com.etao.tools.api.TurnOverApi");
    private static ServletContextEvent _e;
    private Timer timer = null;

    public void contextInitialized(ServletContextEvent sce) {
        _e = sce;
        String time = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
        logger.info("开始发送易淘餐厅营业统计时间：" + time);

        //时间间隔
        long PERIOD_DAY = 24 * 60 * 60 * 1000;
        long temp=1 * 60 * 60 * 1000;
        /*** 定制每日9:00执行方法 ***/
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.HOUR_OF_DAY, 8);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        Date date=calendar.getTime(); //第一次执行定时任务的时间

        //如果第一次执行定时任务的时间 小于 当前的时间
        //此时要在 第一次执行定时任务的时间 加一天，以便此任务在下个时间点执行。如果不加一天，任务会立即执行。
        if (date.before(new Date())) {
            calendar.add(Calendar.DAY_OF_MONTH, 1);
            date = calendar.getTime();
        }
        timer = new Timer(true);
        timer.schedule(new contractTask(), date, PERIOD_DAY);
    }

    public void contextDestroyed(ServletContextEvent sce) {
        String time = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
        logger.info("结束发送易淘餐厅营业统计时间：" + time);
        timer.cancel();
    }

    class contractTask extends TimerTask {
        public void run() {
            try {
                WebApplicationContext context = WebApplicationContextUtils
                        .getRequiredWebApplicationContext(_e.getServletContext());
                ITurnOverService turnOver = (ITurnOverService) context.getBean("TurnOverService");
                turnOver.TurnOverAndSendEmail();
                String time = new SimpleDateFormat("yyyy-MM-dd HH:mm").format(new Date());
                logger.info("发送易淘餐厅营业统计邮箱成功！时间：" + time);
            } catch (Exception e) {
                logger.info("发送易淘餐厅营业统计邮箱失败！原因：" + e.getMessage());
            }
        }
    }


}
